package com.hyh.shiyanshiguanli.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hyh.shiyanshiguanli.Expections.NullException;
import com.hyh.shiyanshiguanli.constant.MessageConstant;
import com.hyh.shiyanshiguanli.domain.dto.PageDTO;
import com.hyh.shiyanshiguanli.domain.dto.StorageAddDTO;
import com.hyh.shiyanshiguanli.domain.entity.*;
import com.hyh.shiyanshiguanli.domain.result.PageResult;
import com.hyh.shiyanshiguanli.mapper.LibAssetMapper;
import com.hyh.shiyanshiguanli.mapper.StorageMapper;
import com.hyh.shiyanshiguanli.service.StorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author hyh
 * @version 1.0
 */
@SuppressWarnings({"ALL"})
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;
    @Autowired
    LibAssetMapper libAssetMapper;

    @Override
    public PageResult page(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPage(),pageDTO.getPageSize());

        Page<Storage> storages = storageMapper.page(pageDTO);

        long total = storages.getTotal();
        List<Storage> result = storages.getResult();

        PageResult result1 = new PageResult();
        result1.setTotal(total);
        result1.setRecodes(result);

        return result1;
    }

    @Transactional
    @Override
    public void add(StorageAddDTO storageAddDTO) {

        if(storageAddDTO.getType() == null || storageAddDTO.getBuyDate() == null){
            throw new NullException(MessageConstant.NULL);
        }

        Integer type = storageAddDTO.getType();
        if (type == 0){
            //如果添加仪器名称型号厂家相同视为一种仪器直接添加数量
            Instrument backInstrument = libAssetMapper.selectByName(storageAddDTO);
            if(backInstrument == null){
                Instrument instrument = new Instrument();
                BeanUtils.copyProperties(storageAddDTO,instrument);
                libAssetMapper.addInstrument(instrument);
            }
            else {
                libAssetMapper.addNum(storageAddDTO.getNum() , backInstrument.getId());
            }
        }
        else  if (type == 1){
            //如果添加仪器名称型号厂家相同视为一种仪器直接添加数量
            Reagent backReagent = libAssetMapper.selectByRName(storageAddDTO);
            if(backReagent == null){
                Reagent reagent = new Reagent();
                BeanUtils.copyProperties(storageAddDTO,reagent);
                libAssetMapper.addReagent(reagent);
            }
            else {
                libAssetMapper.addRNum(storageAddDTO.getNum(), backReagent.getId());
            }
        }
        storageMapper.add(storageAddDTO);
    }
}
